package com.xu.mb3.mbtools;

import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.builder.xml.XMLMapperEntityResolver;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * mybatis 解析xml内置工具类
 *
 * @author xuguan
 * @since 2024/11/13
 */
public class XPathParserSample {


    /**
     * 参考XMLConfigBuilder解析configuration配置文件
     *
     * @see XMLConfigBuilder#parse()
     */
    public static void xPathParserSample() {
        try {
            final InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            final XPathParser xPathParser = new XPathParser(is, true, null, new XMLMapperEntityResolver());

            final XNode root = xPathParser.evalNode("/configuration");
            final XNode propNode = root.evalNode("properties");
            final Properties properties = propNode.getChildrenAsProperties();
            final String resource = propNode.getStringAttribute("resource");
            if (resource != null) {
                properties.putAll(Resources.getResourceAsProperties(resource));
            }
            properties.forEach((key, value) -> System.out.println(key + "=" + value));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        xPathParserSample();
    }
}
